var attrtabshow = {
    all: ["pageattr", "obj", "text", "link", "img"],
    h1: ["obj", "text"],
    h2: ["obj", "text"],
    h3: ["obj", "text"],
    h4: ["obj", "text"],
    h5: ["obj", "text"],
    h6: ["obj", "text"],
    p: ["obj", "text"],
    img: ["obj", "img"],
    a: ["obj", "text", "link"],
};
var current_element=null;
function Obj(type, value, parent) {
    this.type = type;
    this.value = value;
    this.parent = parent;
    this.x = 0;
    this.y = 0;
    this.is_dropping = false;
    this.mouse_offset_x = 0;
    this.mouse_offset_y = 0;
    this.animations=[];
}
Obj.prototype.init = function () {
    this.dom = document.createElement(this.type);
    this.dom.style.userSelect = "none";
    this.dom.style.position = "absolute";
    this.update_pos();
    this.update_value();
    this.dom.addEventListener("mousedown", (e) => {
        this.is_dropping = true;
        current_element=this;
        if($('.active')){
            $('.active').classList.remove('active');
        }
        this.dom.classList.add('active');
        this.mouse_offset_x = this.x - e.x;
        this.mouse_offset_y = this.y - e.y;
        var on_mousemove=document.body.addEventListener("mousemove", (e) => {
            if (this.is_dropping) {
                this.x = e.x + this.mouse_offset_x;
                this.y = e.y + this.mouse_offset_y;
                this.update_pos();
            }
        });
        var on_mouseup=document.body.addEventListener("mouseup", (e) => {
            this.is_dropping = false;
            this.mouse_offset_x = 0;
            this.mouse_offset_y = 0;
            document.body.removeEventListener('mousemove',on_mousemove);
            document.body.removeEventListener('mouseup',on_mouseup);
        });
    });
    
    this.dom.addEventListener("click", (e) => {
        hide_all_attrtab();
        for (var i = 0; i < attrtabshow[this.type].length; i++) {
            $("." + attrtabshow[this.type][i]).style.display = "block";
        }
        $('.obj-x').onchange=()=>{
            this.x=parseInt($('.obj-x').value);
            this.dom.style.left=this.x+"px";
        }
        $('.obj-y').onchange=()=>{
            this.y=parseInt($('.obj-y').value);
            this.dom.style.top=this.y+"px";
        }
        this.set_value();
        this.set_event();
        this.set_animation_tab();
        e.stopPropagation();
    });
    this.dom.ondragstart=()=>{return false;}
    this.parent.appendChild(this.dom);
    this.animation_tab=document.createElement('div');
};
Obj.prototype.update_value = function () {
    this.dom.innerText = this.value;
};
Obj.prototype.update_pos = function () {
    this.dom.style.left = this.x + "px";
    this.dom.style.top = this.y + "px";
};
Obj.prototype.set_value = function () { };
Obj.prototype.set_event = function () { };
Obj.prototype.set_animation_tab=function (){
    var animation_tab=$('.animation-tab');
    animation_tab.innerHTML="";
    animation_tab.appendChild(this.animation_tab);
};

function set_obj_tab(el) {
    $('.obj-x').value = el.style.left.slice(0, el.style.left.length - 2);
    $('.obj-y').value = el.style.top.slice(0, el.style.top.length - 2);
}

function TextObj(type, value, parent) {
    Obj.call(this, type, value, parent);
    this.ctype = "TextObj";
    this.color = "rgb(0,0,0)";
    this.width = "";
}
TextObj.prototype = new Obj("", "", null);
TextObj.prototype.set_value = function () {
    set_obj_tab(this.dom);
    $('.text-color').value = rgbToHex(this.dom.style.color) || "#000000";
    $('.text-text').value = this.dom.innerText || "";
    //$('.text-width').value = this.dom.style.width.slice(0, this.dom.style.width.length - 2);
    $('.text-width').value=this.width;
};
TextObj.prototype.set_event = function () {
    var color_element = $('.text>.text-color');
    var text_element = $('.text>.text-text');
    var width_element = $('.text>.text-width');
    color_element.onchange = (e) => {
        this.dom.style.color = color_element.value;
        this.color = color_element.value;
    };
    text_element.onchange = (e) => {
        this.value = text_element.value;
        this.dom.innerText = text_element.value;
    };
    width_element.onchange = (e) => {
        this.dom.style.width = width_element.value ? width_element.value + "px" : "";
        this.width = width_element.value;
    }
}
TextObj.prototype.to_html = function () {
    var html=format(
        '<{type} style="{width};color:{color};">{text}</{type}>',
        {
            type: this.type,
            width: this.dom.style.width ? "width:" + this.dom.style.width : "",
            color: this.dom.style.color || "rgb(0,0,0)",
            text: this.dom.innerText.replace(/\n/g, '<br>')
        }
    );
    for(var i=0;i<this.animations.length;i++){
        var a=this.animations[i];
        html=a.to_str(html);
    }
    html=format(
        '<el style="position:absolute;top:{y}px;left:{x}px;">{html}</el>',
        {
            x: this.x || "0",
            y: this.y || "0",
            html:html
        }
    )
    return html;
}


function ImgObj(type, value, parent) {
    Obj.call(this, type, value, parent);
    this.ctype = "ImgObj";
    this.src = "";
    this.width = "";
    this.height = "";
    this.show_src=true;
}
ImgObj.prototype = new Obj("", "", null);
ImgObj.prototype.set_value = function () {
    set_obj_tab(this.dom);
    $('.img-width').value = this.dom.style.width.slice(0, this.dom.style.width.length - 2) || 0;
    $('.img-height').value = this.dom.style.height.slice(0, this.dom.style.height.length - 2) || 0;
    if(this.show_src){
        $('.img-src').value = this.dom.getAttribute('src');
    }else{
        $('.img-src').value="剪贴板图像,不显示路径";
    }
};
ImgObj.prototype.set_event = function () {
    $('.img-width').onchange = (e) => {
        this.dom.style.width = $('.img-width').value ? $('.img-width').value + "px" : "";
        this.width = this.dom.style.width;
    };
    $('.img-height').onchange = (e) => {
        this.dom.style.height = $('.img-height').value ? $('.img-height').value + "px" : "";
        this.height = this.dom.style.height;
    }
    if(!this.show_src)return;
    $('.img-src').onchange = (e) => {
        this.src = $('.img-src').value;
        this.dom.setAttribute('src', $('.img-src').value);
    }
}
ImgObj.prototype.to_html = function () {
    var html=format(
        '<img src="{src}" style="position:absolute;top:{y}px;left:{x}px;{width};{height};">',
        {
            src: this.dom.getAttribute('src'),
            x: this.x,
            y: this.y,
            width: this.dom.style.width ? "width:" + this.dom.style.width : "",
            height: this.dom.style.height ? "height:" + this.dom.style.height : ""
        }
    );
    for(var i=0;i<this.animations.length;i++){
        var a=this.animations[i];
        html=a.to_str(html);
    }
    return html;
}


function LinkObj(type, value, parent) {
    Obj.call(this, type, value, parent);
    this.ctype = "LinkObj";
    this.href = "";
    this.color = "";
    this.width = "";
}
LinkObj.prototype = new Obj("", "", null);
LinkObj.prototype.set_value = function () {
    set_obj_tab(this.dom);
    $('.text-color').value = rgbToHex(this.dom.style.color) || "#000000";
    $('.text-text').value = this.dom.innerText || "";
    $('.text-width').value = this.dom.style.width.slice(0, this.dom.style.width.length - 2);
    $('.link-href').value = this.dom.getAttribute('data-href');
};
LinkObj.prototype.set_event = function () {
    var color_element = $('.text>.text-color');
    var text_element = $('.text>.text-text');
    var width_element = $('.text>.text-width');
    color_element.onchange = (e) => {
        this.dom.style.color = color_element.value;
        this.color = this.dom.style.color;
    };
    text_element.onchange = (e) => {
        this.dom.innerText = text_element.value;
        this.value = text_element.value;
    };
    width_element.onchange = (e) => {
        this.dom.style.width = width_element.value ? width_element.value + "px" : "";
        this.width = this.dom.style.width;
    }
    $('.link-href').onchange = (e) => {
        this.href = $('.link-href').value;
        this.dom.setAttribute('data-href', $('.link-href').value);
    }
}
LinkObj.prototype.to_html = function () {
    var html=format(
        '<a href="{href}" style="position:absolute;top:{y}px;left:{x}px;width:{width};color:{color};">{text}</a>',
        {
            type: this.type,
            x: this.x || 0,
            y: this.y || 0,
            width: this.dom.style.width || "abc",
            color: this.dom.style.color || "rgb(0,0,0)",
            text: this.dom.innerText.replace(/\n/g, '<br>'),
            href:this.href
        }
    );
    for(var i=0;i<this.animations.length;i++){
        var a=this.animations[i];
        html=a.to_str(html);
    }
    return html;
}


function create_h(n) {
    if(pages.length==0){
        tip('你必须先创建页面!');
        return;
    }
    var page = $(".page");
    var obj = new TextObj("h" + n, "", page);
    obj.init();
    pages[currentPageIndex].objs.push(obj);
    prompt("创建对象对话框", "请输入对象内容:", (value) => {
        obj.value = value;
        obj.update_value();
    });
    return obj;
}

function create_p() {
    if(pages.length==0){
        tip('你必须先创建页面!');
        return;
    }
    var page = $(".page");
    var obj = new TextObj("p", "", page);
    obj.init();
    pages[currentPageIndex].objs.push(obj);
    // prompt("创建对象对话框", "请输入对象内容:", (value) => {
    //     obj.value = value;
    //     obj.update_value();
    // });
	var html="\
	<h4>创建段落对话框</h4>\
	<p>请输入段落内容:</p>\
	<textarea id='prompt-textarea' style='width:100%;border-radius:10px;'></textarea>\
	"
	alertWindow(html,()=>{
		obj.value=$('#prompt-textarea').value;
		obj.update_value();
	})
    return obj;
}

function create_img() {
    if(pages.length==0){
        tip('你必须先创建页面!');
        return;
    }
    var page = $(".page");
    var obj = new ImgObj("img", "", page);
    obj.init();
    pages[currentPageIndex].objs.push(obj);
    prompt("对象编辑对话框", "请输入图片地址:", (value) => {
        obj.dom.src = value;
        obj.src = value;
    });
    return obj;
}

function create_link() {
    if(pages.length==0){
        tip('你必须先创建页面!');
        return;
    }
    var page = $(".page");
    var obj = new LinkObj("a", "", page);
    obj.init();
    prompt("创建对象对话框", "请输入链接内容:", (value) => {
        obj.value = value;
        obj.update_value();
        pages[currentPageIndex].objs.push(obj);
        prompt("对象编辑对话框", "请输入链接地址:", (value) => {
            obj.dom.setAttribute("data-href", value);
            obj.href = value;
            obj.dom.addEventListener("click", (e) => {
                e.preventDefault();
            });
        });
    });
    return obj;
}

function delete_element() {
    if(!$('.active')){
        tip('你还没有选中任何对象!');
        return;
    }
    var dom = $(".active");
    var objs = pages[currentPageIndex].objs;
    var i;
    for (i = 0; i < objs.length; i++) {
        var obj = objs[i];
        if (obj.dom == dom) {
            break;
        }
    }
    objs.splice(i, 1);
    dom.parentNode.removeChild(dom);
}

function switch_objs() {
    var page = $('.page');
    page.innerHTML = "";
    if (pages.length != 0 && pages[currentPageIndex]) {
        var page_obj = pages[currentPageIndex];
        for (var i = 0; i < page_obj.objs.length; i++) {
            var obj = page_obj.objs[i];
            page.appendChild(obj.dom);
        }
    }
}

function clipboard_init(){
    var clipboard=require('electron').clipboard;
    window.addEventListener('keydown',(e)=>{
        if($(':focus'))return;
        if(e.keyCode==86&&e.ctrlKey){ //ctrl+v
            var data,type;
            if(!clipboard.readImage().isEmpty()){
                type="img"
                data=clipboard.readImage().toDataURL();
            }
            else if(clipboard.readBuffer('FileNameW').length!=0){
                type="img";
                var rawFilePath = clipboard.readBuffer('FileNameW').toString('ucs2');
                var filePath = rawFilePath.replace(new RegExp(String.fromCharCode(0), 'g'), '');
                var v_img=new Image();
                v_img.src='file:///'+filePath;
                var v_canvas=document.createElement('canvas');
                var ctx=v_canvas.getContext('2d');
                v_canvas.width=v_img.width;
                v_canvas.height=v_img.height;
                ctx.drawImage(v_img,0,0);
                data=v_canvas.toDataURL();
            }else if(clipboard.readText()!=""){
                type='text';
                data=clipboard.readText();
            }
            var p=prompt;
            prompt=(a,b,f)=>{f()};
            if(type=="img"){
                var obj=create_img();
                obj.dom.src=data;
                obj.src=data;
                obj.show_src=false;
            }else if(type=="text"){
                var obj=create_p();
                obj.value = data;
                obj.update_value();
            }
            prompt=p;
        }
    })
}

function down_element(){
    var index=pages[currentPageIndex].objs.indexOf(current_element);
    if(index==0)return;
    var last_element=pages[currentPageIndex].objs[index-1];
    pages[currentPageIndex].objs[index-1]=current_element;
    pages[currentPageIndex].objs[index]=last_element;
    last_element.dom.parentNode.insertBefore(current_element.dom,last_element.dom);
}
function up_element(){
    var index=pages[currentPageIndex].objs.indexOf(current_element);
    if(index==pages[currentPageIndex].objs.length-1)return;
    var next_element=pages[currentPageIndex].objs[index+1];
    pages[currentPageIndex].objs[index+1]=current_element;
    pages[currentPageIndex].objs[index]=next_element;
    current_element.dom.parentNode.insertBefore(next_element.dom,current_element.dom);
}
